//
//  WPYBViewController.m
//  wobingwoyi
//
//  Created by WGP on 2016/12/16.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPYBViewController.h"
#import "WPYBindingPhoneVC.h"
#import "SwipeBack.h"
#import "WPYBRecordViewController.h"
#import "WPAfterBingZFBVC.h"
#import "YYLabel.h"
#import "WPSoftwareAgreementVC.h"

@interface WPYBViewController ()

@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UILabel *YBLabel;
@property(nonatomic,strong)UILabel *balanceLabel;

@property(nonatomic,strong)UIImageView *lineImageView1;
@property(nonatomic,strong)UIImageView *lineImageView2;
@property(nonatomic,strong)UIImageView *lineImageView3;

@property(nonatomic,strong)UIButton *YBRecordbtn;
@property(nonatomic,strong)UIButton *aboutYBBtn;
@property(nonatomic,strong)UIButton *exchangeEarningsBtn;
@property(nonatomic,strong)UIButton *coverBtn;
@property(nonatomic,strong)UIView *bottomView;

@property(nonatomic,strong)UIButton *cancelBtn;
@property(nonatomic,strong)YYLabel *agreementLabel;
@property(nonatomic,strong)UIButton *agreementbtn;

@end

@implementation WPYBViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = GlobalBgColor;
    
    [self setupUI];
    
    [self getYBInfo];
}

-(void)setupUI
{
    [self bgView];
    [self setupLabels];
    [self setupBtns];
    
    [self agreementLabel];
}

-(UIView *)bgView
{
    if (_bgView == nil)
    {
        _bgView = [UIView new];
        _bgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bgView];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(64+10);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(232);
        }];
        
        UIImageView *lineImageView1 = [UIImageView lineImageView];
        self.lineImageView1 = lineImageView1;
        UIImageView *lineImageView2 = [UIImageView lineImageView];
        self.lineImageView2 = lineImageView2;
        UIImageView *lineImageView3 = [UIImageView lineImageView];
        self.lineImageView3 = lineImageView3;
        
        [_bgView addSubview:lineImageView1];
        [_bgView addSubview:lineImageView2];
        [_bgView addSubview:lineImageView3];
        
        [lineImageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_bgView);
            make.height.mas_equalTo(0.5);
            make.top.equalTo(_bgView).offset(90);
        }];
        
        [lineImageView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.height.equalTo(lineImageView1);
            make.top.equalTo(lineImageView1).offset(97);
        }];
        
        [lineImageView3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.height.equalTo(lineImageView1);
            make.bottom.equalTo(_bgView);
        }];
        
        
    }
    return _bgView;
}

-(void)setupLabels
{
    UILabel *YBTitleLable = [UILabel new];
    [self.bgView addSubview:YBTitleLable];
    YBTitleLable.text = @"医币余额";
    YBTitleLable.textColor = GLobalFontColor;
    YBTitleLable.font = [UIFont systemFontOfSize:15];
    [YBTitleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgView);
        make.top.equalTo(self.bgView).offset(15);
    }];
    
    self.YBLabel  = [UILabel new];
    self.YBLabel.textColor = RGB_SAME(102);
    self.YBLabel.font = [UIFont systemFontOfSize:30];
    self.YBLabel.text = @"0";
    [self.bgView addSubview:self.YBLabel];
    [self.YBLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgView);
        make.top.equalTo(YBTitleLable.mas_bottom).offset(20);
    }];
    
    UILabel *balanceTitleLabel = [UILabel new];
    [self.bgView addSubview:balanceTitleLabel];
    balanceTitleLabel.text = @"可兑换收益(元)";
    balanceTitleLabel.textColor = GLobalFontColor;
    balanceTitleLabel.font = [UIFont systemFontOfSize:15];
    [balanceTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgView);
        make.top.equalTo(self.lineImageView1).offset(15);
    }];
    
    self.balanceLabel = [UILabel new];
    self.balanceLabel.text = @"0";
    self.balanceLabel.textColor = GlobalColor;
    self.balanceLabel.font = [UIFont systemFontOfSize:30];
    [self.bgView addSubview:self.balanceLabel];
    [self.balanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgView);
        make.top.equalTo(balanceTitleLabel.mas_bottom).offset(23);
    }];
}

-(void)setupBtns
{
    self.YBRecordbtn = [self buttonWith:@"医币记录"];
    self.aboutYBBtn = [self buttonWith:@"关于医币"];
    [self.bgView addSubview:self.YBRecordbtn];
    [self.bgView addSubview:self.aboutYBBtn];
    
    [self.YBRecordbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.lineImageView2);
        make.top.equalTo(self.lineImageView2.mas_bottom);
        make.bottom.equalTo(self.lineImageView3.mas_top);
        make.right.equalTo(self.bgView.mas_centerX);
    }];
    
    [self.aboutYBBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bgView);
        make.top.equalTo(self.lineImageView2.mas_bottom);
        make.bottom.equalTo(self.lineImageView3.mas_top);
        make.left.equalTo(self.bgView.mas_centerX);
    }];
    
    UIImageView *line = [UIImageView lineImageView];
    [self.bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgView);
        make.width.mas_equalTo(0.5);
        make.height.mas_equalTo(45);
        make.centerY.equalTo(self.YBRecordbtn);
    }];
    
    self.exchangeEarningsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.exchangeEarningsBtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
    [self.exchangeEarningsBtn setBackgroundImage:[UIImage imageNamed:@"highLight"] forState:UIControlStateHighlighted];
    [self.exchangeEarningsBtn setTitle:@"兑换收益" forState:UIControlStateNormal];
    self.exchangeEarningsBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.exchangeEarningsBtn];
    [self.exchangeEarningsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.bgView.mas_bottom).offset(80);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
    }];
    [self.exchangeEarningsBtn addTarget:self action:@selector(exchangeEarningsBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *tipLabel = [UILabel new];
    tipLabel.numberOfLines = 0;
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
    paraStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:RGB_SAME(153), NSParagraphStyleAttributeName:paraStyle};
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"注: 医币需要大于或等于2000才能提现哦,提现时\n需要收取30%的手续费" attributes:dic];
    
    tipLabel.attributedText = attStr;
    
    [self.view addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.exchangeEarningsBtn.mas_bottom).offset(20);
    }];
}

-(YYLabel *)agreementLabel
{
    if (_agreementLabel == nil)
    {
        _agreementLabel = [YYLabel new];
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"我已阅读并同意 《用户兑换协议》"];
        NSRange range = [@"我已阅读并同意 《用户兑换协议》" rangeOfString:@"《用户兑换协议》"];
        text.yy_font = [UIFont systemFontOfSize:13];
        text.yy_color = GLobalFontColor;
        [self.view addSubview:_agreementLabel];
        [text yy_setTextHighlightRange:range
                                 color:GlobalColor
                       backgroundColor:GlobalBgColor
                             tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                 
                                 WPSoftwareAgreementVC *vc = [WPSoftwareAgreementVC new];
                                 vc.PageTitle = @"金币兑换协议";
                                 vc.url = @"https://www.wobingwoyi.com:8443/wbwy/page/userAgreement.do";
                                 [self.navigationController pushViewController:vc animated:YES];
                                 
                             }];
        [_agreementLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-35);
            make.centerX.equalTo(self.view);
        }];
        
         _agreementLabel.attributedText = text;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:@"agreementBtn_normal"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"agreementBtn_selected"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(agreementBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:btn];
        btn.selected = YES;
        self.agreementbtn = btn;
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_agreementLabel);
            make.right.equalTo(_agreementLabel.mas_left).offset(-10);
        }];
        
        //监听btn的选中状态
        [btn addObserver:self forKeyPath:@"selected" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    }
    return _agreementLabel;
}

-(void)getYBInfo
{
    
    NSString *url = @"user/findUser.do";
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            NSDictionary *detail = responseObject[@"detail"];
            
            self.YBLabel.text = [NSString stringWithFormat:@"%@",detail[@"coin"]];
            self.balanceLabel.text = [NSString stringWithFormat:@"%@",detail[@"income"]];
        }
        else
        {
            self.YBLabel.text = @"0";
            self.balanceLabel.text = @"0";
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //账号过期
                [self illegalLoginWithSuccessBlock:^{
                    
                    WPMineLoginVC *vc = [WPMineLoginVC new];
                    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                }];
            }
            else
            {
                [self showErrorInfoWithStatus:@"获取失败"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(UIButton *)buttonWith:(NSString *)title
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:GlobalColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchDown];
    return btn;
}

#pragma mark - 按钮响应事件
-(void)btnDidClick:(UIButton *)btn
{
    if (btn == self.YBRecordbtn)
    {
        WPYBRecordViewController *vc = [WPYBRecordViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        WPSoftwareAgreementVC *vc = [WPSoftwareAgreementVC new];
        vc.PageTitle = @"医币介绍";
        vc.url = @"https://www.wobingwoyi.com:8443/wbwy/page/ybsm.do";
        //https://www.wobingwoyi.com:8443/wbwy/
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)exchangeEarningsBtnDidClick
{
    NSString *url = @"user/getBindAccounts.do";
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            if ([responseObject[@"detail"] count])
            {
                //绑定过
                WPAfterBingZFBVC *vc = [WPAfterBingZFBVC new];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else
            {
                //展示体现选择的方式
                [self showMethodOfWithdrawal];
            }
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //账号过期
                [self illegalLoginWithSuccessBlock:^{
                    
                    //点击确定后的回调
                    WPMineLoginVC *vc = [WPMineLoginVC new];
                    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                }];
            }
            else
            {
                [self showErrorInfoWithStatus:@"服务器错误"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)showMethodOfWithdrawal
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.coverBtn = coverBtn;
    coverBtn.backgroundColor = RGBA_COLOR(51, 51, 51, 0.5);
    [window addSubview:coverBtn];
    coverBtn.frame = window.bounds;
    [coverBtn addTarget:self action:@selector(coverBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    
    UIView *bottomView = [UIView new];
    self.bottomView = bottomView;
    bottomView.backgroundColor = [UIColor clearColor];
    [coverBtn addSubview:bottomView];
    bottomView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 185);
    
    UIButton *ZFBBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ZFBBtn setImage:[UIImage imageNamed:@"ZFB_icon"] forState:UIControlStateNormal];
    [ZFBBtn setImage:[UIImage imageNamed:@"ZFB_icon"] forState:UIControlStateHighlighted];
    ZFBBtn.tag = 1000;
    ZFBBtn.backgroundColor = [UIColor whiteColor];
    [ZFBBtn setTitle:@"  支付宝账号绑定" forState:UIControlStateNormal];
    [ZFBBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    ZFBBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:ZFBBtn];
    [ZFBBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(bottomView);
        make.height.mas_equalTo(65);
    }];
    
    UIButton *YLBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [YLBtn setImage:[UIImage imageNamed:@"YL_icon"] forState:UIControlStateNormal];
    [YLBtn setImage:[UIImage imageNamed:@"YL_icon"] forState:UIControlStateHighlighted];
    YLBtn.tag = 1001;
    YLBtn.backgroundColor = [UIColor whiteColor];
    [YLBtn setTitle:@"  银行卡账号绑定" forState:UIControlStateNormal];
    [YLBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    YLBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:YLBtn];
    [YLBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(ZFBBtn);
        make.top.equalTo(ZFBBtn.mas_bottom);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelBtn = cancelBtn;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.tag = 1002;
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bottomView);
        make.height.mas_equalTo(45);
    }];
    
    [ZFBBtn addTarget:self action:@selector(methodBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    [YLBtn addTarget:self action:@selector(methodBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    [cancelBtn addTarget:self action:@selector(methodBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    
    UIImageView *line  = [UIImageView lineImageView];
    [bottomView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.right.equalTo(bottomView);
        make.top.equalTo(bottomView).offset(65);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        bottomView.frame = CGRectMake(0, SCREEN_HEIGHT-185, SCREEN_WIDTH, 185);
    }];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if([keyPath isEqualToString:@"selected"])
    {
       self.exchangeEarningsBtn.enabled = [change[@"new"] intValue];
    }
}

#pragma mark - 按钮点击事件
-(void)agreementBtnDidClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
}

-(void)coverBtnDidClick:(UIButton *)btn
{
    [UIView animateWithDuration:0.25 animations:^{
        
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 185);
        btn.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        
        [btn removeFromSuperview];
    }];

}

-(void)methodBtnDidClick:(UIButton *)btn
{
    //未
    [UIView animateWithDuration:0.25 animations:^{
        
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 185);
        self.coverBtn.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        [self.coverBtn removeFromSuperview];
        
        if (btn.tag == 1000)
        {
            //兑换收益
            WPYBindingPhoneVC *vc = [WPYBindingPhoneVC new];
            vc.method = 0;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if(btn.tag == 1001)
        {
            //兑换收益
            WPYBindingPhoneVC *vc = [WPYBindingPhoneVC new];
            vc.method = 1;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
    
}

-(void)dealloc
{
    [self.agreementbtn removeObserver:self forKeyPath:@"selected"];
}

@end
